package com.yqz.sys.service.impl;

import com.yqz.common.CodeMsg;
import com.yqz.common.Result;
import com.yqz.common.base.Form;
import com.yqz.common.base.Query;
import com.yqz.common.base.service.impl.BaseServiceImpl;
import com.yqz.common.util.WebUtil;
import com.yqz.sys.form.CompRoleForm;
import com.yqz.sys.mapper.CompRoleMapper;
import com.yqz.sys.mapper.CompRolePermRefMapper;
import com.yqz.sys.mapper.CompUserRoleRefMapper;
import com.yqz.sys.query.CompRoleQuery;
import com.yqz.sys.service.CompRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CompRoleServiceImpl extends BaseServiceImpl implements CompRoleService {

    @Autowired
    private CompRoleMapper roleMapper;

    @Autowired
    private CompRolePermRefMapper rolePermRefMapper;

    @Autowired
    private CompUserRoleRefMapper userRoleRefMapper;

    public CompRoleServiceImpl(CompRoleMapper roleMapper) {
        super(roleMapper);
    }

    @Override
    public Result queryPage(Query query) {
        CompRoleQuery compRoleQuery = (CompRoleQuery) query;
        compRoleQuery.setCompId(WebUtil.getCurrentCompUser().getCompId());
        return super.queryPage(compRoleQuery);
    }

    @Override
    public Result add(Form form) {
        CompRoleForm compRoleForm = (CompRoleForm) form;
        compRoleForm.setCompId(WebUtil.getCurrentCompUser().getCompId());
        return super.add(compRoleForm);
    }

    @Override
    public Result delete(Integer id) {
        Integer count = userRoleRefMapper.findCountByRId(id);
        if(count > 0){
            return new Result(CodeMsg.ROLE_DELETE_USEING_ERROR);
        }
        return super.delete(id);
    }

    @Override
    @Transactional
    public Result setRolePerm(Integer rId, List<Integer> pId) {
        //删除所有角色权限信息
        rolePermRefMapper.deleteById(rId);
        //重新添加角色权限信息
        rolePermRefMapper.batchInsert(rId,pId,WebUtil.getCurrentCompUser().getCompId());
        return new Result();
    }
}
